import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import '../services/ScreenAdapter.dart';
import '../config/Config.dart';
import '../widget/LoadingWidget.dart';
import '../services/SearchServices.dart';

class ProductListPage extends StatefulWidget {
  Map arguments;

  ProductListPage({this.arguments});

  @override
  State<StatefulWidget> createState() =>
      _ProductListPageState(arguments: arguments);
}

class _ProductListPageState extends State<ProductListPage> {
  Map arguments;
  int _topCurrentIndex = 0;
  List productList = [];
  int page = 1;
  int pageSize = 5;
  String sort = '';
  bool flag = true;
  bool hasMore = true;
  bool hasData = true;

  //  继承跳转页面传的值
  _ProductListPageState({this.arguments});

  //  配置search搜索框的值
  var _initKeyWordsController = new TextEditingController();

  //  用户上拉分页
  ScrollController _scrollController = new ScrollController();

  //  控制右侧抽屉
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();


  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Container(
          alignment: Alignment.center,
          height: ScreenAdapter.height(68),
          padding: EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: Colors.black12,
            borderRadius: BorderRadius.circular(34),
          ),
          child: TextField(
              controller: this._initKeyWordsController,
              style: TextStyle(fontSize: ScreenAdapter.size(34)),
              autofocus: true,
              decoration: InputDecoration(
                  border: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(34)
                  )
              ),
          ),
        ),
        actions: [
          Container(
            alignment: Alignment.center,
            height: ScreenAdapter.height(68),
            margin: EdgeInsets.only(right: 10),
            child: InkWell(
              child: Text('搜索',style:TextStyle(fontSize: ScreenAdapter.size(34))),
              onTap: (){
                this.setState(() {
                  _topCurrentIndex = 0;
                  productList = [];
                  page = 1;
                  sort = '';
                  flag = true;
                  hasMore = true;
                });
                //  获取商品数据
                _getProductList();

                //  将搜索记录保存到内存中
                SearchServices.setHistoryData(_initKeyWordsController.text);
              },
            ),
          )
        ],
      ),
      body: Stack(
        children: [
          //  列表内容区域
          _showProduct(),

          //  顶部横向自定义定位导航
          _subHeadWidget(),
        ],
      ),
      endDrawer: Drawer(
        child: Container(
          margin: EdgeInsets.all(10),
          child: Text('123'),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();

    // 给search框值赋值
    arguments['keyWords'] == null ? _initKeyWordsController.text =  '' : _initKeyWordsController.text =  arguments['keyWords'];

    //  获取商品数据
    _getProductList();

    //监听滚动事件，打印滚动位置
    _scrollController.addListener(() {
      //  滚动条位置大于20像素
      if (_scrollController.position.pixels > _scrollController.position.maxScrollExtent -20 ) {
        if(this.flag && this.hasMore){
          _getProductList();
        }
      }
    });
  }

  //  列表内容区域
  _showProduct(){
    if (hasData){
      return this.productList.length > 0 ? _productListWidget() : LoadingWidget();
    } else {
      return Center(
        child: Text('没有您要浏览的数据...'),
      );
    }

  }

  //  获取商品数据
  _getProductList() async {
    this.setState(() {
      flag = false;
    });

    String api = '';

    if (arguments['keyWords'] != null){
      if (this.sort == '' ){
        api = '${Config.domain}api/plist?search=${_initKeyWordsController.text}&page=${this.page}&pageSize=${this.pageSize}';
      } else {
        api = '${Config.domain}api/plist?search=${_initKeyWordsController.text}&page=${this.page}&pageSize=${this.pageSize}&sort=${this.sort}';
      }

    } else {
      if (this.sort == '') {
        api =
        '${Config.domain}api/plist?cid=${arguments['cid']}&page=${this.page}&pageSize=${this.pageSize}';
      } else {
        api =
        '${Config.domain}api/plist?cid=${arguments['cid']}&page=${this.page}&pageSize=${this.pageSize}&sort=${this.sort}';
      }
    }

    var focusData = await Dio().get(api);
    var res = focusData.data['result'];

    // 是否有数据
    if(res.length == 0) {
      this.setState(() {
        hasData = false;
      });
    } else {
      this.setState(() {
        hasData = true;
      });
    }

    // 请求数据小于每页数据，没有更多数据了
    if (res.length < this.pageSize){
      this.setState(() {
        productList.addAll(res);
        flag = true;
        hasMore = false;
      });
    } else {
      this.setState(() {
        productList.addAll(res);
        page += 1;
        flag = true;
      });
    }
  }

  //  列表内容区域
  Widget _productListWidget() {
    return Container(
      margin: EdgeInsets.only(top: ScreenAdapter.height(100)),
      padding: EdgeInsets.all(10),
      child: ListView.builder(
          controller: _scrollController,
          itemCount: productList.length,
          itemBuilder: (context, index) {
            String sPic = productList[index]['s_pic'];
            return Column(
              children: [
                Row(
                  children: [
                    Container(
                      width: ScreenAdapter.width(180),
                      height: ScreenAdapter.height(180),
                      child: Image.network(
                          '${Config.domain + sPic.replaceAll('\\', '/')}',
                          fit: BoxFit.cover),
                    ),
                    Expanded(
                      flex: 1,
                      child: Container(
                        margin: EdgeInsets.only(left: 10),
                        height: ScreenAdapter.height(180),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('${productList[index]['title']}',
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(fontSize: 12)),
                            Row(
                              children: [
                                Container(
                                  height: ScreenAdapter.height(36),
                                  margin: EdgeInsets.only(right: 10),
                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(10),
                                      color:
                                          Color.fromRGBO(230, 230, 230, 0.9)),
                                  child: Text('4g',
                                      style: TextStyle(fontSize: 12)),
                                ),
                                Container(
                                  height: ScreenAdapter.height(36),
                                  margin: EdgeInsets.only(right: 10),
                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(10),
                                      color:
                                          Color.fromRGBO(230, 230, 230, 0.9)),
                                  child: Text('126',
                                      style: TextStyle(fontSize: 12)),
                                ),
                              ],
                            ),
                            Text('￥${productList[index]['price']}',
                                style:
                                    TextStyle(fontSize: 12, color: Colors.red)),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                Divider(height: 20),
                _showMore(index),
              ],
            );
          }),
    );
  }

  //  显示更多
  _showMore(index){
    if (this.hasMore){
      return index == this.productList.length-1 ? LoadingWidget() : Text('');
    } else {
      return index == this.productList.length-1 ? Text('我是有底线的') : Text('');
    }
  }

  //  顶部横向自定义定位导航
  Widget _subHeadWidget() {
    return Positioned(
      top: 0,
      height: ScreenAdapter.height(100),
      width: ScreenAdapter.height(750),
      child: Container(
        height: ScreenAdapter.height(100),
        width: ScreenAdapter.height(750),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Expanded(
              flex: 1,
              child: InkWell(
                child: Container(
                  alignment: Alignment.center,
                  height: ScreenAdapter.height(100),
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                    color: _topCurrentIndex == 0 ? Colors.red : Colors.black12,
                  ))),
                  child: Text('综合',
                      style: TextStyle(
                          color: _topCurrentIndex == 0
                              ? Colors.red
                              : Colors.black54)),
                ),
                onTap: () {
                  this.setState(() {
                    _topCurrentIndex = 0;
                    sort = '';
                    hasMore = true;
                    productList = [];
                    page = 1;
                    //  获取商品数据
                    _getProductList();
                  });
                },
              ),
            ),
            Expanded(
              flex: 1,
              child: InkWell(
                child: Container(
                  alignment: Alignment.center,
                  height: ScreenAdapter.height(100),
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                    color: _topCurrentIndex == 1 ? Colors.red : Colors.black12,
                  ))),
                  child: Text('销量',
                      style: TextStyle(
                          color: _topCurrentIndex == 1
                              ? Colors.red
                              : Colors.black54)),
                ),
                onTap: () {
                  this.setState(() {
                    _topCurrentIndex = 1;
                    sort =
                        sort == 'salecount_1' ? 'salecount_-1' : 'salecount_1';
                    hasMore = true;
                    productList = [];
                    page = 1;
                    //  获取商品数据
                    _getProductList();
                  });
                },
              ),
            ),
            Expanded(
              flex: 1,
              child: InkWell(
                child: Container(
                  alignment: Alignment.center,
                  height: ScreenAdapter.height(100),
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                    color: _topCurrentIndex == 2 ? Colors.red : Colors.black12,
                  ))),
                  child: Text('价格',
                      style: TextStyle(
                          color: _topCurrentIndex == 2
                              ? Colors.red
                              : Colors.black54)),
                ),
                onTap: () {
                  this.setState(() {
                    _topCurrentIndex = 2;
                    sort = sort == 'price_1' ? 'price_-1' : 'price_1';
                    hasMore = true;
                    productList = [];
                    page = 1;
                    //  获取商品数据
                    _getProductList();
                  });
                },
              ),
            ),
            Expanded(
              flex: 1,
              child: InkWell(
                child: Container(
                  alignment: Alignment.center,
                  height: ScreenAdapter.height(100),
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                    color: _topCurrentIndex == 3 ? Colors.red : Colors.black12,
                  ))),
                  child: Text('筛选',
                      style: TextStyle(
                          color: _topCurrentIndex == 3
                              ? Colors.red
                              : Colors.black54)),
                ),
                onTap: () {
                  this.setState(() {
                    _topCurrentIndex = 3;
                  });
                  // 打开右边抽屉
                  _scaffoldKey.currentState.openEndDrawer();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
